﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lamex.Common;
using Lamex.Library;
using Lamex.Core;
using Lamex;
//using Lamex.Bridge;
using Lamex.Interface;
//using Lamex.SystemManager.BLL;
//using Lamex.SystemManager.Model;
//using Lamex.SystemManager.Interface;
using Lamex.Base;
using System.Diagnostics;
using DevExpress.XtraEditors;
using System.Net;
using System.Management;

namespace Lamex
{
    public partial class Login : frmBase
    {
        //test01
        //private ILoginAuthorization _CurrentAuthorization = null;
        ILoginAuthorization _CurrentLoginInfo = new LoginSystemAuth();
        int iLanguage = 0;
        public Login()
        {
            InitializeComponent();
            LoadSkin();
            Lamex.Common.IniFile ini = new Common.IniFile(Application.StartupPath + "\\config\\CSFramework3.ini");
            iLanguage = int.Parse(ini.IniReadValue("Configuration", "ChangeLanguage").ToString());
            DataTable dt = new DataTable();
            dt.Columns.Add("ipAddress", typeof(string));
            dt.Columns.Add("dbName", typeof(string));
            //DataRow dr2 = dt.NewRow();
            //dr2["ipAddress"] = ".";
            //dr2["dbName"] = "Local";
            //dt.Rows.Add(dr2);
            DataRow dr = dt.NewRow();
            dr["ipAddress"] = "172.23.134.29";
            if (iLanguage == 0)
                dr["dbName"] = "测试数据库";
            else
                dr["dbName"] = "Testing DataBase";
            dt.Rows.Add(dr);
            DataRow dr1 = dt.NewRow();

            dr1["ipAddress"] = "172.23.134.36";
            if (iLanguage == 0)
                dr1["dbName"] = "正式数据库";
            else
                dr1["dbName"] = "Product DataBase";
            dt.Rows.Add(dr1);
            lpDatabase.Properties.ValueMember = "ipAddress";
            lpDatabase.Properties.DisplayMember = "dbName";
            lpDatabase.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("dbName"));
            lpDatabase.Properties.DataSource = dt;
            lpDatabase.Properties.ShowHeader = false;


            string recordName = ini.IniReadValue("Configuration", "RecoredName").ToString();
            string recoredPassWord = ini.IniReadValue("Configuration", "RecoredPassWord").ToString();
            //MD5解密
            String isMD5Checked = ini.IniReadValue("Configuration", "MD5Checked").ToString();
            if (!string.IsNullOrEmpty(isMD5Checked))
                recoredPassWord = Lamex.Common.EncryptionMD5.EncryptionDES.DecryptStringReverse(recoredPassWord);

            string isChecked = ini.IniReadValue("Configuration", "Checked").ToString();

            if (isChecked == "1")
            {
                if (!string.IsNullOrEmpty(recordName))
                {
                    txtUserName.Text = ini.IniReadValue("Configuration", "RecoredName").ToString();
                    txtPassWord.Text = recoredPassWord;//ini.IniReadValue("Configuration", "RecoredPassWord").ToString();
                    chkPassWord.Checked = true;
                    //lpDatabase.EditValue = ini.IniReadValue("SQL Configuration", "SqlServer").ToString();
                }
            }
            //string macAddress1 = GetMacAddress();
            //if (macAddress1 != Loginer.CurrentUser.MacAddress)
            //{
            //    txtUserName.Text = "";
            //    txtPassWord.Text = "";
            //}
            lpDatabase.EditValue = ini.IniReadValue("SQL Configuration", "SqlServer").ToString();
            btnLongModify.Visible = false;
            chkModify.CheckedChanged += new EventHandler(chkModify_CheckedChanged);
            btnLongModify.Click += new EventHandler(btnLongModify_Click);
            if (iLanguage == 0)
            {
                this.Text = "MES管理平台";
                lbeUserName.Text = "用   户：";
                lblPassWord.Text = "密   码：";
                lblDatabase.Text = "数据库：";
                chkPassWord.Text = "记住密码";
                btnLogin.Text = "登录";
                btnCancel.Text = "取消";
                btnLongModify.Text = "修改密码";
                chkModify.Text = "修改密码";

            }
            else
            {
                this.Text = "MES Manager Platform";
                lbeUserName.Text = "User:";
                lblPassWord.Text = "PassWord:";
                lblDatabase.Text = "DataBase:";
                chkPassWord.Text = "Remember";
                btnLogin.Text = "Login";
                btnCancel.Text = "Cancel";
                btnLongModify.Text = "Modify";
                chkModify.Text = "ModifyPWD";
            }
        }

        private void chkModify_CheckedChanged(object sender, EventArgs e)
        {
            if (chkModify.Checked == true)
            {
                this.Visible = false;
                Main.frmModify frm = new Main.frmModify(txtUserName.Text);
                frm.ShowDialog();
                this.Visible = true;
                chkModify.Checked = false;
            }



        }
        private void btnLongModify_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            Main.frmModify frm = new Main.frmModify(txtUserName.Text);
            frm.ShowDialog();
            this.Visible = true;
        }
        public static bool _Login()
        {
            Login login = new Login();
            DialogResult result = login.ShowDialog();
            bool ret = (result == DialogResult.OK);
            return ret;

        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            //***加计时器，计时
            Stopwatch sw = new Stopwatch();
            sw.Start();

            //Lamex.Common.IniFile ini = new Common.IniFile(Application.StartupPath + "\\CSFramework3.ini");
            //string recordName= ini.IniReadValue("Configuration", "RecoredName").ToString();
            //string recoredPassWord= ini.IniReadValue("Configuration", "RecoredPassWord").ToString();
            //if (!string.IsNullOrEmpty(recordName))
            //txtUserName.Text = ini.IniReadValue("Configuration", "RecoredName").ToString();
            //txtPassWord.Text = ini.IniReadValue("Configuration", "RecoredPassWord").ToString();
            try
            {
                if (false == BridgeFactory.InitializeBridge())//初始化桥接功能
                {
                    return;
                }

                #region 是否更新版本
                ProcessStartInfo processStartInfo = new ProcessStartInfo()
                {
                    FileName = "MAutoUpdate.exe",//自动更新程序名称-固定  MAutoUpdate
                    Arguments = " Lamex.Main 0" //参数信息,程序名称 0：弹窗更新 1：静默更新
                };
                Process proc = Process.Start(processStartInfo);
                if (proc != null)
                {
                    proc.WaitForExit();
                }
                #endregion
                //ProcessStartInfo processStartInfo = new ProcessStartInfo()
                //{
                //    FileName = "MAutoUpdate.exe",//自动更新程序名称-固定  MAutoUpdate
                //    Arguments = " Lamex.Main 0" //参数信息,程序名称 0：弹窗更新 1：静默更新
                //};
                //Process proc = Process.Start(processStartInfo);
                //if (proc != null)
                //{
                //    proc.WaitForExit();
                //}

                if (string.IsNullOrEmpty(txtUserName.Text))
                {
                    MsgShow.Warning("输入用户名不能为空！");
                    return;
                }
                if (string.IsNullOrEmpty(txtPassWord.Text))
                {
                    MsgShow.Warning("输入密码不能为空！");
                    return;
                }
                if (string.IsNullOrEmpty(lpDatabase.Text))
                {
                    MsgShow.Warning("数据库不能为空！");
                    return;
                }
                string userID = txtUserName.Text;
                string password = txtPassWord.Text;
                /*MD5常规加密*/
                string Encrypassword = Lamex.Common.EncryptionMD5.EncryptionDES.EncryptStringReverse(password);
                Lamex.Common.IniFile ini = new Common.IniFile(Application.StartupPath + "\\config\\CSFramework3.ini");
                ini.IniWriteValue("SQL Configuration", "SqlServer", lpDatabase.EditValue.ToString());
                //var s = bridge.GetFirsttEntriyList();
                //生产环境连接配置
                IWriteSQLConfigValue cfgNormal = new IniFileWriter(Application.StartupPath + SqlConfiguration.INI_CFG_PATH);

                //设置配置信息

                SqlConfiguration.SetSQLConfig(cfgNormal);
                

                //Lamex.Common.Loginer.CurrentUser.

                LoginUser loginUser = new LoginUser(userID, password, null, null);
                loginUser.DataSetID = "1";


                //********************************


                //*********************************
                //IUser bridge = BridgeFactory.CreateUserBridge();
                //Lamex.Model.TUserInfo user = new Lamex.Model.TUserInfo();
                //user.isid=18;
                //user.Account = "lzw0502232";
                //user.FlagAdmin = "s";
                //user.Email = "lizhongwa@126.com";
                //user.Address = "利扬123";
                //bool isfalg = BaseFactory<TUser>.Instance.Update(user);

                //if( bridge.Update(user))
                //{
                //    MessageBox.Show("SS");
                //}


                if (_CurrentLoginInfo.Login(loginUser))
                {
                    string macAddress = GetMacAddress();
                    
                    if (macAddress == Loginer.CurrentUser.MacAddress)
                    {


                        if (chkPassWord.Checked == true)
                        {
                            ini.IniWriteValue("Configuration", "RecoredName", userID);
                            ini.IniWriteValue("Configuration", "RecoredPassWord", Encrypassword);
                            ini.IniWriteValue("Configuration", "Checked", "1");
                            ini.IniWriteValue("Configuration", "MD5Checked", "1");
                            



                        }
                        else
                        {
                            ini.IniWriteValue("Configuration", "RecoredName", "");
                            ini.IniWriteValue("Configuration", "RecoredPassWord", "");
                            ini.IniWriteValue("Configuration", "Checked", "0");
                            ini.IniWriteValue("Configuration", "MD5Checked", "");
                            
                        }
                    }
                    else
                    {
                        chkPassWord.Checked = false;
                        //return;
                    }
                    //if (ipadrlist[1].ToString() != Loginer.CurrentUser.IPAddress)
                    //{
                    //    XtraMessageBox.Show("本机IP和帐号不在同一台电脑上！");
                    //    return;
                    //}
                    if (lpDatabase.EditValue.ToString().Contains("36"))
                    {
                        if (iLanguage == 0)
                            Lamex.Common.Loginer.CurrentUser.DBName = "正式数据库";
                        else
                            Lamex.Common.Loginer.CurrentUser.DBName = "Product DataBase";
                    }

                    else if (lpDatabase.EditValue.ToString().Contains("29"))
                    {
                        if (iLanguage == 0)
                            Lamex.Common.Loginer.CurrentUser.DBName = "测试数据库";
                        else
                            Lamex.Common.Loginer.CurrentUser.DBName = "Testing DataBase";
                    }

                    else if (lpDatabase.EditValue.ToString().Contains("."))
                        Lamex.Common.Loginer.CurrentUser.DBName = "本地数据库";
                    ini.IniWriteValue("SQL Configuration", "SqlServer", "172.23.134.36");
                    Loginer.CurrentUser.DataSetID = lpDatabase.EditValue.ToString();
                    Loginer.CurrentUser.ChangeLanguage = iLanguage;
                    Program.MainForm = new frmMainForm();//登录成功创建主窗体
                    Program.MainForm.InitUserInterface(new LoadStatus(lblStatus));
                    this.DialogResult = DialogResult.OK; //成功
                    this.Close(); //关闭登陆窗体

                    sw.Stop();
                    //TimeSpan tt = sw.Elapsed;
                    //DevExpress.XtraEditors.XtraMessageBox.Show("登录成功，用时：" + Math.Round(tt.TotalMilliseconds).ToString() + "毫秒！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    //this.ShowLoginInfo("登录失败，请检查用户名和密码!");
                    //MsgShow.Warning("登录失败，请检查用户名和密码!");
                    return;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }



        /// <summary>  
        /// 获取本机MAC地址  
        /// </summary>  
        /// <returns>本机MAC地址</returns>  
        public string GetMacAddress()
        {
            try
            {
                string strMac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        strMac = mo["MacAddress"].ToString();
                        strMac = strMac.Replace(':', '-');
                    }
                }
                moc = null;
                mc = null;
                return strMac;
            }
            catch
            {
                return "unknown";
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)   //  if (e.KeyValue == 13) 判断是回车键
            {
                if (string.IsNullOrEmpty(txtUserName.Text))
                {
                    MsgShow.Warning("输入用户名不能为空！");
                    return;
                }
                this.txtPassWord.Focus();
            }
        }

        private void txtPassWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(txtPassWord.Text))
                {
                    MsgShow.Warning("输入密码不能为空！");
                    return;
                }
                btnLogin_Click(null, null);
            }
        }

        private void lpDatabase_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void btnLongModify_Click_1(object sender, EventArgs e)
        {

        }

        private void lblStatus_Click(object sender, EventArgs e)
        {

        }
    }
}
